package com.example.demo.hawkeye;


import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 百度地图相关API
 */
public class BaiduApi {

    private static Logger logger = LoggerFactory.getLogger(BaiduApi.class);

    private static Map<String, String> baseBody = new HashMap<>();

    static {
        baseBody.put("ak", "VnNdal8oEf6Xr3no6Aakx63VrVu64gZV");
       // baseBody.put("service_id", "223354");
    }

    /**
     * 百度鹰眼 - 增加实体
     */
    public static void addEntity() {
        String url = "http://yingyan.baidu.com/api/v3/entity/add";
        Map<String, String> body = MapUtil.createMap(HashMap.class);
        body.putAll(baseBody);
        body.put("entity_name", "ToyotaCorolla");
        body.put("entity_desc", "粤A88990");

        String params = makeRequestParams(body);
        logger.info("#request body: "+params);
        HttpResponse execute = HttpUtil.createPost(url).body(params).execute();
        logger.info(execute.body());
    }

    public static void updateEntity() {
        String url = "http://yingyan.baidu.com/api/v3/entity/update";
        Map<String, String> body = MapUtil.createMap(HashMap.class);
        body.putAll(baseBody);
        body.put("entity_name", "ToyotaCorolla");
        body.put("entity_desc", "粤A88888");

        String params = makeRequestParams(body);
        logger.info("#request body: "+params);
        HttpResponse execute = HttpUtil.createPost(url).body(params).execute();
        logger.info(execute.body());
    }

    public static void geocoding() {
        String url = "http://api.map.baidu.com/geocoding/v3";
        Map<String, String> body = MapUtil.createMap(HashMap.class);
        body.putAll(baseBody);
        body.put("output", "json");
        body.put("address", "北京市海淀区上地十街10号");

        String params = makeRequestParams(body);
        logger.info("#request body: "+params);
        HttpResponse execute = HttpUtil.createGet(url).body(params).execute();
        logger.info(execute.body());
    }

    /**
     * 将参数map转换为百度参数串
     * @param paramsMap
     * @return
     */
    public static String makeRequestParams(Map<String, String> paramsMap) {
        StringBuilder paramsBody = new StringBuilder();
        Set<String> keySet = paramsMap.keySet();
        for (String key : keySet) {
            paramsBody.append(key).append("=").append(paramsMap.get(key)).append("&");
        }
        int i = paramsBody.lastIndexOf("&");
        paramsBody.deleteCharAt(i);
        return paramsBody.toString();
    }

    public static void main(String[] args) {
        BaiduApi.geocoding();
    }
}
